package com.fast.develop.dm.core;

import com.fast.develop.dm.meta.MetaDomainModel;
import com.fast.develop.dm.meta.exception.DomainModelException;
import com.fast.develop.dm.meta.loader.MetaModelLoader;
import com.fast.develop.dm.core.reader.MetaFileReader;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;
import java.util.*;

/**
 * @author 莫寅
 * @createTime 2022-06-04 23:41
 * @desc：
 */
public class MetaDomainConfiguration {

    private MetaModelLoader metaModelLoader;

    private List<MetaDomainModel> metaDomainModels = new ArrayList<>();

    private Map<String, MetaDomainModel> metaDomainModelType = new HashMap<>();

    private boolean initialized = false;

    private MetaFileReader metaFileReader;

    public MetaDomainConfiguration() {
        this.metaModelLoader = new MetaModelLoader();
        this.metaFileReader = new MetaFileReader();
    }

    public MetaDomainConfiguration addInputStream(InputStream xmlInputStream)  {
        metaFileReader.getMetaDomainSources().addInputStream( xmlInputStream );
        return this;
    }

    public MetaDomainConfiguration addFolderPath(String path) {
        metaFileReader.getMetaDomainSources().addFolderPath(path);
        return this;
    }

    public void build() {
        if(initialized){
            throw new DomainModelException("已初始化！");
        }

        metaFileReader.read();
        List<InputStream> jsonInputStreams = metaFileReader.getSchemas();

        jsonInputStreams.forEach(inputStream -> {
            JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
            MetaDomainModel metaDomainModel = metaModelLoader.load(rawSchema);
            metaDomainModels.add(metaDomainModel);
            metaDomainModelType.put(metaDomainModel.getName(), metaDomainModel);
        });

        initialized = true;
    }

    public List<MetaDomainModel> getMetaDomainModels(){
        return new ArrayList<>(metaDomainModelType.values());
    }

}
